package agenda.modelo;

import javax.management.Query;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class MainHibernate {

	static Session session;

	public static void main(String[] args) {

		SessionFactory sessionFactory;

		Configuration configuration = new Configuration();
		configuration.configure();

		ServiceRegistry sr = new StandardServiceRegistryBuilder()
				.applySettings(configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(sr);

		session = sessionFactory.openSession();

		consultaConTelefono(3);

		agregaContacto();

		agregaConDomicilio();

		agregaConTelefonos();

		session.close();
		sessionFactory.close();

	}

	public static void consultaConTelefono(int id) {
		Contacto c = (Contacto) session.get(Contacto.class, id);

		System.out.println(c.getIdContacto());
		System.out.println(c.getNombre());
		System.out.println(c.getDom().getVia());
		String[] tel = c.getTelefono();

		for (int i = 0; i < tel.length; i++) {
			System.out.println(tel[i]);
		}

	}

	public static void agregaContacto() {

		Contacto c = new Contacto();
		c.setNombre("Pablo");
		c.setApellidos("Lopez");
		c.setApodo("Sin mas datos");

		session.beginTransaction();

		session.persist(c);

		session.getTransaction().commit();

	}

	public static void agregaConDomicilio() {

		Contacto c = new Contacto();
		c.setNombre("Antonio");
		c.setApellidos("Marcos");
		c.setApodo("Solo con Domicilio");

		Domicilio d = new Domicilio();
		d.setCiudad("Alcobendas");
		d.setCodigoPostal("29000");
		d.setNumero(69);
		d.setPiso(5);
		d.setProvincia("Madrid");
		d.setPuerta("A");
		d.setTipoVia("Avenida");
		d.setVia("San Martin");

		c.setDom(d);

		session.beginTransaction();

		session.persist(c);

		session.getTransaction().commit();

	}

	public static void agregaConTelefonos() {

		Contacto c = new Contacto();
		c.setNombre("Cecilia");
		c.setApellidos("Bontempo");
		c.setApodo("Domicilio y Telefonos");

		Domicilio d = new Domicilio();
		d.setCiudad("Meco");
		d.setCodigoPostal("28800");
		d.setNumero(16);
		d.setPiso(0);
		d.setProvincia("Madrid");
		d.setPuerta("");
		d.setTipoVia("calle");
		d.setVia("Holanda");

		c.setDom(d);

		c.setTelefono(new String[] { "680559561", "918307918" });

		session.beginTransaction();

		session.persist(c);

		session.getTransaction().commit();

		// session.beginTransaction();
		// session.delete(pro);
		// session.update(pro);

		// session.getTransaction().commit();
	}
}
